import Vue from "vue";
import axios from "axios";
import router from "../router";
import store from "../store";
import common from "../utils/common";
import {Toast} from "vant";
// import FingerprintJS from '@fingerprintjs/fingerprintjs';

Vue.use(Toast);

axios.defaults.timeout = 300000; //请求超时5秒
axios.defaults.baseURL = process.env.VUE_APP_URL;
axios.defaults.headers.post["Content-Type"] =
    "application/x-www-form-urlencoded"; //设置post请求是的header信息

// axios.defaults.withCredentials = true

var _bus = new Vue();
var num = 0;

//http request 拦截器
axios.interceptors.request.use(
    (config) => {
      // let apiUrl = process.env.VUE_APP_URL, orginUrl = window.location.origin, orginName = window.location.hostname;
      // if (process.env.NODE_ENV == 'production' || process.env.NODE_ENV == 'test') {
      //   let newUrl = apiUrl;
      //   if (orginName.indexOf('www') != -1) {
      //     newUrl = orginUrl.replace('www', 'api')
      //   } else if (orginName.indexOf('h5') != -1) {
      //     newUrl = orginUrl.replace('h5', 'api')
      //   } else {
      //     newUrl = `https://api.${orginName}`
      //   }

      //   apiUrl = newUrl + '/api/';
      //   config.baseURL = apiUrl;
      // }
      // console.log(process.env.NODE_ENV, '环境')
      // console.log(orginUrl, 'H5链接')
      // console.log(config.baseURL, 'api接口')
      let token = store.state.token;
      let lang = "en_US";
      let locale = localStorage.getItem("language") || "en_US";
      let visitorIds = localStorage.getItem("visitorIds") || "";

      lang = locale;

      let timestamp = new Date().getTime();
      // let obj = new Object();

      if (config.isUpload) {
        var obj = new Object();
      } else {
        var obj = Object.assign({}, config.data);
      }

      obj.timestamp = timestamp;
      // obj.apiKey = "test";
      // obj.apiKey = "panda-api";

      if (process.env.NODE_ENV == "production") {
        obj.apiKey = "test";
      } else {
        obj.apiKey = "test";
      }

      // 去掉签名对象里面的空值，未定义字段
      for (var key in obj) {
        if (obj[key] === "" || undefined === obj[key] || null === obj[key]) {
          delete obj[key];
        }
      }
      obj.sign = common.sign(obj);

      // 判断PC
      let systemState = "h5";
      const device = navigator.userAgent;
      if (device.indexOf("iPad") > -1) {
        //  ipad
      } else if (device.indexOf("Android") > -1 || device.indexOf("ios") > -1) {
        // 手机
      } else {
        // 电脑
        systemState = "pc";
      }

      // 获取设备的一个唯一标识
      // let visitorId = '';
      // getvisitorId();
      // async function getvisitorId() {
      //     const fp = await FingerprintJS.load()
      //     const result = await fp.get()
      //     // return result.visitorId
      //     visitorId = result.visitorId

      // }

      if (token) {
        // 判断是否存在token，如果存在的话，则每个http header都加上token
        // 判断是否是upload模式，如果是则需要改为form-data格式

        if (config.isUpload) {
          let formData = new FormData(); //new一个formData事件
          formData.append("file", config.data);
          formData.append("sign", obj.sign);
          formData.append("timestamp", obj.timestamp);
          formData.append("apiKey", obj.apiKey);
          config.data = formData;
          config.headers = {
            "Content-Type": "multipart/form-data",
            "device-id": visitorIds,
            system: systemState,
            token,
            lang,
          };
        } else {
          config.data = obj;
          config.data = JSON.stringify(config.data);
          config.headers = {
            "Content-Type": "application/json",
            "device-id": visitorIds,
            system: systemState,
            token,
            lang,
          };
        }
        num++;
        _bus.$emit("showloading");
      } else {
        config.data = obj;
        config.headers = {
          "Content-Type": "application/json",
          "device-id": visitorIds,
          system: systemState,
          lang,
        };
      }
      return config;
    },
    (err) => {
      return Promise.reject(err);
    }
);

axios.interceptors.response.use(
    (response) => {
      num--;

      if (num <= 0) {
        _bus.$emit("closeLoading");
      } else {
        _bus.$emit("showloading");
      }
      if (response.data.code === 401) {
        // Toast({
        //   message: '请登录！',
        //   timeout: 1500,
        // });
        store.dispatch("resetVuex");
        // if(!store.state.isApp){
        //   store.dispatch('resetVuex');
        // } else {
        //   let appResult = {
        //     code: response.data.code
        //   };
        //   common.callBackApp(appResult);
        //   return response;
        // }
        // else app提供的方法

        router.push({
          path: "/user/login"
        });
        // setTimeout(function(){
        //   router.push({
        //     path:"/user/login",
        //     querry:{redirect: router.currentRoute.fullPath}//从哪个页面跳转
        //   })
        // }, 1500);

        return response;
      }
      // if (response.data.code === -1) {
      //   localStorage.removeItem('token')
      //   router.push({
      //     path:"/login",
      //     querry:{redirect: router.currentRoute.fullPath}//从哪个页面跳转
      //   })
      // }
      return response;
    },
    (err) => {
      _bus.$emit("closeLoading");
      num--;

      if (err.code === "ECONNABORTED" && err.message.indexOf("timeout") !== -1) {
        Toast({
          message: "Error:500",
          timeout: 1500,
        });
      }
      return Promise.reject(err);
    }
);

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}, headers = {}) {
  return new Promise((resolve, reject) => {
    axios
        .get(url, {
          params: params,
          headers: headers,
        })
        .then((response) => {
          resolve(response.data);
        })
        .catch((err) => {
          reject(err);
        });
  });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}, config = {isUpload: false}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data, config).then(
        (response) => {
          resolve(response.data);
        },
        (err) => {
          reject(err);
        }
    );
  });
}

export var bus = _bus;
